package com.lib.base.utils.image

import android.content.Context
import androidx.core.content.ContextCompat
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool
import com.bumptech.glide.load.engine.cache.ExternalPreferredCacheDiskCacheFactory
import com.bumptech.glide.load.engine.cache.LruResourceCache
import com.bumptech.glide.module.AppGlideModule

@GlideModule
class MyAppGlide : AppGlideModule() {

    override fun applyOptions(context: Context, builder: GlideBuilder) {
        builder.setDiskCache(
            ExternalPreferredCacheDiskCacheFactory(
                context,
                diskCacheFolderName(context),
                diskCacheSizeBytes().toLong()
            )
        )
            .setMemoryCache(LruResourceCache(memoryCacheSizeBytes().toLong()))
            .setBitmapPool(LruBitmapPool(memoryCacheSizeBytes().toLong()))
    }

    /**
     * Returns `true` if Glide should check the AndroidManifest for [GlideModule]s.
     *
     *
     * Implementations should return `false` after they and their dependencies have migrated
     * to Glide's annotation processor.
     *
     *
     * Returns `true` by default.
     */
    override fun isManifestParsingEnabled(): Boolean {
        return false
    }


    private fun memoryCacheSizeBytes(): Int {
        // 20 MB
        return 1024 * 1024 * 20
    }

    private fun diskCacheSizeBytes(): Int {
        // 512 MB
        return 1024 * 1024 * 512
    }

    private fun diskCacheFolderName(context: Context): String {
        return ContextCompat.getCodeCacheDir(context).path + "/qsos"
    }
}